const { Controller } = require('egg');
const { menuPrompt } = require('../utils/prompt');

class ChatController extends Controller {
  // 流式聊天接口
  async streamChat() {
    console.log('menuPrompt',menuPrompt);
    const { ctx } = this;
    // 'deepseek-r1:8b'
    const { prompt = '', model = 'qwen3:0.6b', pages = [] } = ctx.request.body;
    // console.log('pages', pages);

    // 设置SSE响应头
    ctx.set('Content-Type', 'text/event-stream');
    ctx.set('Cache-Control', 'no-cache');
    ctx.set('Connection', 'keep-alive');
    ctx.status = 200;

    // 原生SSE实现
    // .replace('#{menuList}', JSON.stringify(pages)),
    const res = ctx.res;
    const messages = [{
      role: 'system',
      content: menuPrompt.replace('&&{menuList}', JSON.stringify(pages)),
    }, {
      role: 'user',
      content: prompt,
    }];
    console.log('messages', messages);
    try {
      // 调用Ollama API
      const response = await fetch('http://192.168.1.160:11434/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          model,
          messages,
          stream: true,
          response_format: {
            type: 'json_object',
          },
        }),
      });

      if (!response.ok) {
        const error = await response.text();
        throw new Error(`Ollama API error: ${response.status} - ${error}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          // 发送结束事件
          res.write('event: end\n');
          res.write('data: {}\n\n');
          break;
        }
        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        // 处理多行响应
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (!line.trim()) continue;

          try {
            const parsed = JSON.parse(line);
            // console.log('parsed', parsed);
            // 处理普通消息
            if (parsed.message.content) {
              res.write('event: message\n');
              res.write(
                `data: ${JSON.stringify({
                  content: parsed.message.content,
                  done: parsed.done,
                })}\n\n`
              );
            }
            // 发送结束事件
            if (parsed.done) {
              res.write('event: end\n');
              res.write('data: {}\n\n');
            }
          } catch (err) {
            // 发送解析错误
            res.write('event: error\n');
            res.write(
              `data: ${JSON.stringify({
                message: '解析错误',
              })}\n\n`
            );
          }
        }
      }
    } catch (err) {
      res.write('event: error\n');
      res.write(
        `data: ${JSON.stringify({
          message: err.message,
        })}\n\n`
      );
    } finally {
      // 注意：不要关闭res，因为SSE连接需要保持
    }
  }
}

module.exports = ChatController;
